class Ke {
  getTimestamp (milli?: boolean): number {
    const t: number = new Date().valueOf()
    return milli ? t : Math.ceil(t / 1000)
  }

  getRandom (min: number, max: number): number {
    return Math.floor(Math.random() * max + min)
  }

  randomString (len: number) {
    len = len || 32
    const $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    const maxPos = $chars.length
    let pwd = ''
    for (let i = 0; i < len; i++) {
      pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
    }
    return pwd
  }

  array () {
    return {
      update (list: any[], key: any, data: any, pk: string = 'id') {
        const index = list.findIndex(_ => _[pk] === key)
        if (index >= -1) {
          list.splice(index, 1, { ...list[index], ...data })
        }
      },
      delete (list: any[], key: any, pk: string = 'id') {
        const index = list.findIndex(_ => _[pk] === key)
        if (index >= -1) {
          list.splice(index, 1)
        }
      },
      tree (
        list: any[],
        id: string = 'id',
        pid: string = 'pid',
        children: string = 'children'
      ) {
        if (!list) {
          return []
        }
        const arr: any = JSON.parse(JSON.stringify(list))
        const map: any = {}
        for (let i = 0; i < arr.length; i++) {
          map[arr[i][id]] = arr[i]
        }
        const newArray: any = []
        const f = () => {
          for (let i = 0; i < arr.length; i++) {
            const parent = map[arr[i][pid]]
            if (parent) {
              (parent[children] || (parent[children] = [])).push(arr[i])
            } else {
              newArray.push(arr[i])
            }
          }
        }
        f()
        return newArray
      }
    }
  }
}

export const ke = new Ke()
